import { parse, compileTemplate } from '@vue/compiler-sfc';
import fs from 'node:fs';
import path from 'node:path';
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
import { getAppCode } from './envReader.mjs'


// 假设的别名到路径的映射
const aliasMappings = {
    '@': 'src', // 假设 '@' 是 'src/' 目录的别名
    // 可以添加更多的别名映射
};

// 解析路径，包括别名
function resolvePath(importPath, currentFilePath) {
    // 替换别名
    for (const [alias, actualPath] of Object.entries(aliasMappings)) {
        if (importPath.startsWith(alias)) {
            importPath = path.join(process.cwd(), actualPath, importPath.substring(alias.length));
            break;
        }
    }
    return path.resolve(path.dirname(currentFilePath), importPath);
}

// 解析.vue文件中的import语句和defineAsyncComponent调用
function resolveImports(scriptContent, filePath) {
    const imports = {};
    // 匹配静态import和defineAsyncComponent调用
    const importRegex = /import\s+(\w+)\s+from\s+['"](.+?)['"]|defineAsyncComponent\s*\(\s*\(\s*\)\s*=>\s*import\s*\(\s*['"](.+?)['"]\s*\)\s*\)/g;
    let match;

    while ((match = importRegex.exec(scriptContent))) {
        let componentName, componentPath;

        if (match[1] && match[2]) {
            // 静态import
            componentName = match[1];
            componentPath = match[2];
        } else if (match[3]) {
            // defineAsyncComponent
            componentName = match[3].split('/').pop().replace('.vue', '');
            componentPath = match[3];
        }

        if (componentPath) {
            // 解析路径，包括别名
            const resolvedPath = resolvePath(componentPath, filePath);
            // 如果解析的路径是一个.vue文件，则添加到imports对象中
            if (resolvedPath.endsWith('.vue')) {
                imports[componentName] = resolvedPath;
            }
        }
    }

    return imports;
}

function kebabToPascalCase(str) {
    return str
        .split('-') // 按照短横线分割字符串
        .map(part => part.charAt(0).toUpperCase() + part.slice(1)) // 将每部分的首字母大写
        .join(''); // 合并成一个字符串
}

const componentNameMap = {
    'TBtnGroup': 'TButtonGroup',
    'TBtnDropdown': 'TButtonDropdown',
    'TRepeat': ['TInfiniteScroll', 'TList'] // 特殊情况返回多个组件
};


// 递归函数来解析.vue文件并收集组件
function _collectComponents(filePath, components = new Set()) {
    if (!fs.existsSync(filePath) || !filePath.endsWith('.vue')) {
        return components;
    }
    const content = fs.readFileSync(filePath, 'utf8');
    const { descriptor } = parse(content);

    let imports = {};

    // 解析<script>部分的imports
    if (descriptor.script || descriptor.scriptSetup) {
        const scriptContent = [
            descriptor.script ? descriptor.script.content : '',
            descriptor.scriptSetup ? descriptor.scriptSetup.content : ''
        ].join('\n');

        imports = resolveImports(scriptContent, filePath);
    }

    // 对解析出的每个组件路径递归调用collectComponents
    Object.values(imports).forEach(importPath => {
        _collectComponents(importPath, components);
    });

    // 解析template部分的组件
    if (descriptor.template) {
        const { ast } = compileTemplate({ source: descriptor.template.content });

        // 遍历AST节点
        const traverseNodes = (node) => {
            switch (node.type) {
                case 0: // ROOT
                    (node.children || []).forEach(traverseNodes);
                    break;
                case 1: // ELEMENT
                    if (node.tagType === 1 && node.tag.startsWith("t-")) {
                        const pascalName = kebabToPascalCase(node.tag);
                        const mapped = componentNameMap[pascalName];

                        if (mapped) {
                            if (Array.isArray(mapped)) {
                                mapped.forEach(c => components.add(c));
                            } else {
                                components.add(mapped);
                            }
                        } else {
                            components.add(pascalName);
                        }
                    }
                    if (node.children) {
                        node.children.forEach(traverseNodes);
                    }
                    break;

                case 9: // IF
                    node.branches.forEach((branch) => traverseNodes(branch));
                    break;

                case 10: // IF_BRANCH
                    if (node.children) {
                        node.children.forEach(traverseNodes);
                    }
                    break;

                case 11: // FOR
                    if (node.children) {
                        node.children.forEach(traverseNodes);
                    }
                    break;
            }
        };

        if (ast) {
            traverseNodes(ast);
        }
    }

    return components;
}

function genDependencies(pageName, components) {
    const appCode = getAppCode("VITE_APP_CODE")
    try {
        const depFilePath = `./src/pages/${pageName}/dependencies.js`
        if (!fs.existsSync(depFilePath)) {
            let depString = `{
                components: ${JSON.stringify(Array.from(components))},//页面中用到的组件，编译时自动抽取覆盖
                renderType: 2,// 0：代表pc，1：代表mobile，2：响应式
                pageType: 'Page', // Page:页面， UIControl：用户组件， Portlet：门户小部件
                appCode: '${appCode}',//关键应用
                LoadContainerSdk:true // 加载容器sdk,支持T，微信，支付宝
            }`
            fs.writeFileSync(depFilePath, `module.exports = ${depString}`, () => { })
        } else {
            // 如果已经存在，我们只更新 components 字段,并且强制appcode为sext
            let dependencies
            try {
                dependencies = require(path.resolve(depFilePath))
            } catch (ex) {
                dependencies = { components: [] }
                console.log(ex)
            }

            let depString = `{
                components: ${JSON.stringify(Array.from(components))},//页面中用到的组件，编译时自动抽取覆盖
                renderType: ${dependencies.renderType},// 0：代表pc，1：代表mobile，2：响应式
                pageType: '${dependencies.pageType}', // Page:页面， UIControl：用户组件， Portlet：门户小部件
                appCode: '${dependencies.appCode}',//关键应用
                LoadContainerSdk:${dependencies.LoadContainerSdk} // 加载容器sdk,支持T，微信，支付宝
            }`
            fs.writeFileSync(depFilePath, `module.exports = ${depString}`, () => { })
        }


    } catch (e) { }
}

export function collectComponents(pageName) {
    const vueFilePath = `./src/pages/${pageName}/${pageName}.vue`;
    if (!fs.existsSync(vueFilePath)) {
        console.warn(`Warning: 未找到和文件夹同名的vue文件 ${vueFilePath}。`);
        return;
    }
    const components = _collectComponents(vueFilePath);
    genDependencies(pageName, components)

}
